package com.moco.launcher.activity;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.moco.launcher.R;
import com.moco.launcher.alarm.Alarm;
import com.moco.launcher.alarm.BaseActivity;
import com.moco.launcher.alarm.Constant;
import com.moco.launcher.alarm.Database;
import com.moco.launcher.alarm.NumericWheelAdapter;
import com.moco.launcher.alarm.OnWheelChangedListener;
import com.moco.launcher.alarm.OnWheelScrollListener;
import com.moco.launcher.alarm.WheelView;
import com.oazon.common.Logger;

public class AlarmAddActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = "AlarmAddActivity";
	
	private ImageButton btnAlarmCancel, btnAlarmConfirm;
	private TextView txtViewAlarmToneName;
	private LinearLayout layoutAlarmTone, layoutAlarmToneName, layoutAlarmTimeLL;
	private ListAdapter listAdapter;
	private ListView listView;
	private Alarm alarm;
	private MediaPlayer mediaPlayer;
	private CountDownTimer alarmToneTimer;
	private String[] strAlarmTones;
	private String[] strAlarmTonePaths;

	private boolean bTimeChanged = false;
	private boolean bTimeScrolled = false;
	Calendar newAlarmTime = Calendar.getInstance();

	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.alarm_activity_add);
		
		mContext = this;
		btnAlarmCancel = (ImageButton) findViewById(R.id.alarm_cancel);
		btnAlarmConfirm = (ImageButton) findViewById(R.id.alarm_add_confirm);
		layoutAlarmTone = (LinearLayout) findViewById(R.id.alarm_tone);
		layoutAlarmToneName = (LinearLayout) findViewById(R.id.alarm_tone_name);
		txtViewAlarmToneName = (TextView) findViewById(R.id.alarm_tone_name_tv);
		layoutAlarmTimeLL = (LinearLayout) findViewById(R.id.alarm_time_ll);
		selectedTime();
		// alarmTimeText = (TextView)findViewById(R.id.alarm_time_tv);
		btnAlarmCancel.setOnClickListener(this);
		btnAlarmConfirm.setOnClickListener(this);
		layoutAlarmTone.setOnClickListener(this);
		layoutAlarmToneName.setOnClickListener(this);
		layoutAlarmTimeLL.setOnClickListener(this);
		// getAlarmTones();
		setMathAlarm(new Alarm());
		// setListAdapter(new AlarmPreferenceListAdapter(this, getMathAlarm()));

	}

	private void selectedTime() {

		final WheelView hours = (WheelView) findViewById(R.id.alarm_hour);
		hours.setAdapter(new NumericWheelAdapter(0, 23, "%02d"));
		// hours.setLabel("hours");
		hours.setCyclic(true);

		final WheelView mins = (WheelView) findViewById(R.id.alarm_mins);
		mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
		// mins.setLabel("mins");
		mins.setCyclic(true);

		Calendar c = Calendar.getInstance();
		int curHours = c.get(Calendar.HOUR_OF_DAY);
		int curMinutes = c.get(Calendar.MINUTE);

		hours.setCurrentItem(curHours);
		mins.setCurrentItem(curMinutes);

		OnWheelChangedListener wheelListener = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				if (!bTimeScrolled) {
					bTimeChanged = true;
					Logger.d(TAG, "HOURS= " + hours.getCurrentItem());
					Logger.d(TAG, "mins= " + mins.getCurrentItem());
					newAlarmTime.set(Calendar.HOUR_OF_DAY,
							hours.getCurrentItem());
					newAlarmTime.set(Calendar.MINUTE, mins.getCurrentItem());
					newAlarmTime.set(Calendar.SECOND, 0);
					alarm.setAlarmTime(newAlarmTime);
					bTimeChanged = false;
				}
			}
		};

		hours.addChangingListener(wheelListener);
		mins.addChangingListener(wheelListener);

		OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
			public void onScrollingStarted(WheelView wheel) {
				bTimeScrolled = true;
			}

			public void onScrollingFinished(WheelView wheel) {
				bTimeScrolled = false;
				bTimeChanged = true;
				Logger.d(TAG, "1HOURS= " + hours.getCurrentItem());
				Logger.d(TAG, "1mins= " + mins.getCurrentItem());

				newAlarmTime.set(Calendar.HOUR_OF_DAY, hours.getCurrentItem());
				newAlarmTime.set(Calendar.MINUTE, mins.getCurrentItem());
				newAlarmTime.set(Calendar.SECOND, 0);
				alarm.setAlarmTime(newAlarmTime);
				bTimeChanged = false;
			}
		};

		hours.addScrollingListener(scrollListener);
		mins.addScrollingListener(scrollListener);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Constant.RESULT_CODE) {
			String path = data.getStringExtra("ring_uri");
			String alarmTone = data.getStringExtra("alarm_tone");
			handleRing(path, alarmTone);
		}
	}

	private void handleRing(String path, String alarmTone) {
		alarm.setAlarmTonePath(path);
		txtViewAlarmToneName.setText(alarmTone);
		
		if (alarm.getAlarmTonePath() != null) {
			if (mediaPlayer == null) {
				mediaPlayer = new MediaPlayer();
			} else {
				if (mediaPlayer.isPlaying())
					mediaPlayer.stop();
				mediaPlayer.reset();
			}
			try {
				mediaPlayer.setVolume(0.2f, 0.2f);
				mediaPlayer.setDataSource(AlarmAddActivity.this,
						Uri.parse(alarm.getAlarmTonePath()));
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mediaPlayer.setLooping(false);
				mediaPlayer.prepare();
				mediaPlayer.start();

				// Force the mediaPlayer to stop after 3
				// seconds...
				if (alarmToneTimer != null)
					alarmToneTimer.cancel();
				alarmToneTimer = new CountDownTimer(3000, 3000) {
					@Override
					public void onTick(long millisUntilFinished) {

					}

					@Override
					public void onFinish() {
						try {
							if (mediaPlayer.isPlaying())
								mediaPlayer.stop();
						} catch (Exception e) {

						}
					}
				};
				alarmToneTimer.start();
			} catch (Exception e) {
				try {
					if (mediaPlayer.isPlaying())
						mediaPlayer.stop();
				} catch (Exception e2) {

				}
			}
		}
	}

	private void getAlarmTones() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				RingtoneManager ringtoneMgr = new RingtoneManager(
						AlarmAddActivity.this);

				ringtoneMgr.setType(RingtoneManager.TYPE_ALARM);

				Cursor alarmsCursor = ringtoneMgr.getCursor();

				strAlarmTones = new String[alarmsCursor.getCount() + 1];
				strAlarmTones[0] = "Silent";
				strAlarmTonePaths = new String[alarmsCursor.getCount() + 1];
				strAlarmTonePaths[0] = "";

				if (alarmsCursor.moveToFirst()) {
					do {
						strAlarmTones[alarmsCursor.getPosition() + 1] = ringtoneMgr
								.getRingtone(alarmsCursor.getPosition())
								.getTitle(AlarmAddActivity.this);
						strAlarmTonePaths[alarmsCursor.getPosition() + 1] = ringtoneMgr
								.getRingtoneUri(alarmsCursor.getPosition())
								.toString();
					} while (alarmsCursor.moveToNext());
				}
				Logger.d("AlarmAddActivity", "Finished Loading "
						+ strAlarmTones.length + " Ringtones.");
				alarmsCursor.close();

			}
		}).start();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.alarm_cancel:
			this.finish();
			break;
		case R.id.alarm_add_confirm:
			Database.init(getApplicationContext());
			if (getMathAlarm().getId() < 1)
				Database.create(getMathAlarm());
			else
				Database.update(getMathAlarm());
			
			alarm.setAlarmActive(true);
			callMathAlarmScheduleService();
			Toast.makeText(AlarmAddActivity.this,
					getMathAlarm().getTimeUntilNextAlarmMessage(),
					Toast.LENGTH_LONG).show();
			finish();
			break;
		case R.id.alarm_tone_name:
		case R.id.alarm_tone:
			Intent intent = new Intent();
			intent.setClass(AlarmAddActivity.this, RingActivity.class);
			startActivityForResult(intent, Constant.RESULT_CODE);
			break;
		case R.id.alarm_time_ll:
			break;
		}
	}

	public ListAdapter getListAdapter() {
		return listAdapter;
	}

	public ListView getListView() {
		if (listView == null)
			listView = (ListView) findViewById(android.R.id.list);
		return listView;
	}

	public void setListView(ListView listView) {
		this.listView = listView;
	}

	public Alarm getMathAlarm() {
		return alarm;
	}

	public void setMathAlarm(Alarm alarm) {
		this.alarm = alarm;
	}
}
